home *** CD-ROM | disk | FTP | other *** search
- Path: mayne.ugrad.cs.ubc.ca!not-for-mail
- From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
- Newsgroups: comp.lang.c
- Subject: Re: Check if a file exists?
- Date: 15 Apr 1996 11:32:19 -0700
- Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
- Message-ID: <4ku4njINNmse@mayne.ugrad.cs.ubc.ca>
- References: <4kp7pg$upe@news-s01.ny.us.ibm.net> <4ktl40$b76@texas.nwlink.com>
- NNTP-Posting-Host: mayne.ugrad.cs.ubc.ca
-
- In article <4ktl40$b76@texas.nwlink.com>,
- Teresa Reiko <tjr19@mail.nwlink.com> wrote:
- >bfilone@ibm.net <Bruce Filone> wrote:
- >>Is it possible in C to check if a file exists other than checking for a >succesful
- >>fopen? ON a unix machine, I just want to know if a file is there or not, >do not
- >>to read or write anything to it. similar to the -f test in unix? I was >hoping for
- >>something less costly than opening and closing if exists because I am >checking
- >>for the existance of many files during the run of a process
- >>Did not see any postings that seemed to refer to this.
- >
- >Use rename():
- >
- >You could try to rename it, and if that fails it's not there,
- >if it works it exists, and then you can rename it back.
-
- Then you need a good temporary name from tmpnam() to make sure you don't
- clobber an existing file. There are potential race conditions in the use of
- tmpnam(): you have to check that the name does not, in fact, exist, before you
- use it, which leads you to circular regress.
-
- >Or, you can create a temporary file, try to rename it to the
- >name of the file you're testing, if it fails it exists, and
-
- Even if you could do this using strictly ANSI/ISO C functionality, on a UNIX
- system, renaming the temporary file to the name of the file you are testing is
- deadly. It _always_ succeeds (modulo the requisite permissions, and acts of
- God). If the original file existed, it is _gone_!
-
- >if it works it wasn't there, and then you can rename it back.
-
- No you can't! :)
-
- And anyway, ANSI/ISO C doesn't give you a way to create a temporary file whose
- name you *know* for the purposes of renaming.
-
- The tmpfile() standard function returns an open file pointer. There is no
- standard mechanism to access the name of this file for the purpose of renaming
- another file to it. So to do the (destructive) operation you describe, you
- would have to rely on UNIX- or BSD-isms like mkstemp(), which makes a temporary
- file _and_ opens it in one step. Or you would have to do a spin loop, whereby
- you keep trying to make up temporary names until you get one that is not in
- use. And that requires an existence check, of course...
-
- >This should be faster than fopen, but you would need to have
- >write access to all the files you're testing.
-
- Why would any of this be faster than a simple fopen?
-